<script setup lang="ts">
import { ref } from 'vue'
import { Refresh, Search, Plus } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import FormRole from '@/components/form/FormRole.vue'
import { rolesDelete, rolesList, rolesMenusSave, rolesSave } from '@/api/interface/web/roles'
import FormRoleMenu from '@/components/view/FormRoleMenu.vue'

const fullscreenLoading = ref(false)

const baseTableRef = ref()

const searchForm = ref<any>({})

const conditionMethod = () => {
  const cond: any = {}
  Object.keys(searchForm.value).map((key) => {
    if (searchForm.value[key] || searchForm.value[key] === 0) {
      cond[key] = searchForm.value[key]
    }
  })
  return cond
}

const handleSearch = () => {
  baseTableRef.value.refresh()
}

const handleResetSearch = () => {
  searchForm.value = {}
  baseTableRef.value.refresh()
}

const dialogFormVisible = ref(false)
const addEditData = ref<any>(null)
const addEditStatus = ref('add')
const roleFormRef = ref()

const handleAdd = () => {
  dialogFormVisible.value = true
  addEditData.value = null
  addEditStatus.value = 'add'
}

const handleEdit = (row: any) => {
  dialogFormVisible.value = true
  addEditData.value = row
  addEditStatus.value = 'edit'
}

const handleDialogFormSubmit = () => {
  roleFormRef.value.submitForm().then((data: any) => {
    if (data) {
      fullscreenLoading.value = true
      if (addEditStatus.value === 'add') {
        rolesSave(data)
          .then(() => {
            dialogFormVisible.value = false
            ElMessage({
              type: 'success',
              message: '新增成功',
            })
            baseTableRef.value.refresh()
          })
          .finally(() => {
            fullscreenLoading.value = false
          })
      } else {
        rolesSave(data)
          .then(() => {
            dialogFormVisible.value = false
            ElMessage({
              type: 'success',
              message: '更新成功',
            })
            baseTableRef.value.refreshStay()
          })
          .finally(() => {
            fullscreenLoading.value = false
          })
      }
    }
  })
}

const handleDialogFormClose = () => {
  dialogFormVisible.value = false
}

const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定删除角色?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    autofocus: false,
  }).then(() => {
    fullscreenLoading.value = true
    const { id } = row
    rolesDelete({ id })
      .then(() => {
        ElMessage({
          message: '删除成功!',
          type: 'success',
        })
        baseTableRef.value.refreshStay()
      })
      .finally(() => {
        fullscreenLoading.value = false
      })
  })
}

const drawerMenuVisible = ref(false)
const roleId = ref<any>(null)
const roleMenuRef = ref()

const selectMenu = (row: any) => {
  roleId.value = `${row.id}`
  drawerMenuVisible.value = true
}

const handleMenuDrawerClose = () => {
  drawerMenuVisible.value = false
}

const handleMenuDrawerSubmit = () => {
  const data = roleMenuRef.value.submitForm()
  console.log(data)
  const keys: any = data.map((v: any) => {
    return {
      roleId: roleId.value,
      menuId: v.id,
      menuParentId: v.parentid,
    }
  })
  if (keys && keys.length) {
    fullscreenLoading.value = true
    rolesMenusSave(keys)
      .then(() => {
        drawerMenuVisible.value = false
        ElMessage({
          message: '保存成功!',
          type: 'success',
        })
      })
      .finally(() => {
        fullscreenLoading.value = false
      })
  } else {
    ElMessage.error('权限勾选不能为空!')
  }
}
</script>

<template>
  <BasePageWrapper v-loading.fullscreen="fullscreenLoading">
    <BasePage>
      <template #title>角色管理</template>
      <template #toolbar>
        <el-button type="primary" @click="handleAdd">
          <template #icon>
            <el-icon><Plus /></el-icon>
          </template>
          新增
        </el-button>
      </template>
      <template #searchbar>
        <el-form :inline="true" :model="searchForm" @submit.prevent>
          <el-form-item label="角色名：">
            <el-input v-model="searchForm.name" placeholder="请输入角色名" />
          </el-form-item>
          <el-form-item>
            <el-button type="info" text bg @click="handleResetSearch">
              <template #icon>
                <el-icon><Refresh /></el-icon>
              </template>
              重置
            </el-button>
            <el-button type="primary" @click="handleSearch">
              <template #icon>
                <el-icon><Search /></el-icon>
              </template>
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </template>

      <BaseTable
        ref="baseTableRef"
        :init-table-method="rolesList"
        :condition-method="conditionMethod"
        storage-condition
      >
        <el-table-column prop="id" label="编号" min-width="180" show-overflow-tooltip>
        </el-table-column>
        <el-table-column
          prop="name"
          label="名称"
          min-width="180"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column prop="remark" label="描述" min-width="200" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="160"> </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" min-width="160"> </el-table-column>
        <el-table-column label="操作" width="210">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="primary" link @click="selectMenu(scope.row)">分配Web权限</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </BaseTable>
    </BasePage>
  </BasePageWrapper>
  <BaseDialog v-model="dialogFormVisible">
    <template #title>{{ addEditStatus === 'add' ? '新增' : '编辑' }}</template>
    <template #buttons>
      <el-button type="info" text bg @click="handleDialogFormClose">取消</el-button>
      <el-button type="primary" @click="handleDialogFormSubmit">确认</el-button>
    </template>
    <FormRole ref="roleFormRef" :data="addEditData" :status="addEditStatus"></FormRole>
  </BaseDialog>

  <BaseDrawer v-model="drawerMenuVisible">
    <template #title>分配Web权限</template>
    <template #footer>
      <el-button type="info" text bg @click="handleMenuDrawerClose">取消</el-button>
      <el-button type="primary" @click="handleMenuDrawerSubmit">确认</el-button>
    </template>
    <FormRoleMenu ref="roleMenuRef" :role-id="roleId"></FormRoleMenu>
  </BaseDrawer>
</template>

<style lang="scss" scoped>
.icon-text-box {
  display: flex;
  justify-content: center;
  align-items: center;

  .icon-text {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 24px;
    cursor: pointer;
    .icon {
      margin-right: 5px;
      font-size: 16px;
    }
    .text {
      width: unset;
    }
  }
  .icon-text:last-child {
    margin-right: 0;
  }
  .icon-text.info {
    color: var(--theme-color);
  }
  .icon-text.delete {
    color: #f56c6c;
  }
}
</style>
